<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="author" content="lijinbo" />
    <title>038-监听屏幕旋转</title>
    <style></style>
  </head>

  <body>
    <div class="box1">js 监听屏幕旋转</div>
    <p>
      <a href="/collection/101-200/142-移动端横屏竖屏css检测/142-index.html">移动端横屏竖屏css检测</a>
    </p>
    <script>
      // js监听屏幕旋转的方案
      console.log(screen.orientation)
      console.log(screen.orientation.angle) // [0竖屏]  [90向左横屏]    [-90/270向右横屏]   [180倒屏]

      function screenChange() {
        if (window.orientation === 90) {
          console.log('这是竖屏')
        }
        if (window.orientation === 0) {
          console.log('这是横屏')
        }
      }
      if ('onorientationchange' in window) {
        window.onorientationchange = screenChange
      } else if ('screen' in window && 'orientation' in window.screen) {
        // 在平板Surface上onorientationchange无法监听，可监听window.screen.orientation的change事件。
        window.screen.orientation.addEventListener('change', screenChange, false)
      } else {
        window.addEventListener('resize', screenChange, false)
      }
    </script>
  </body>
</html>
